﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InHD.model;
using System.ComponentModel;
using System.Windows.Input;
using System.Windows.Documents;
using InHD.commands;
using InHD.utilities;
using InHD.dataaccess;
using System.Data;
using System.IO;

namespace InHD.viewmodels
{
    class RegisterStep1:WorkspaceViewModel, IDataErrorInfo
    {
        private InvoiceTemplateRepository _invoiceTemplateRepository = new InvoiceTemplateRepository();
        private ManagementUnitRepository _mngUnitRepository = new ManagementUnitRepository();
        private List<InvoiceTemplate> _invoiceTemplateCollection = new List<InvoiceTemplate>();
        private InvoiceTemplate _invoiceTemplate = InvoiceTemplate.CreateNewInvoiceTemplate();
        private RegisterInfo _regInfo;
        readonly CompanyInfo _companyInfo;
        public string commandExcuted;
        public string RegResult { get; set; }

        #region Constructor

        public RegisterStep1(RegisterPrinting registerPrinting, CompanyInfo companyInfo, RegisterInfo regInfo)
        {
            _registerPrinting = registerPrinting;
            _companyInfo = companyInfo;
            _regInfo = regInfo;
            InvoiceTemplateField = InvoiceTemplate.Fields;
            if (string.IsNullOrEmpty(_mngUnitRepository.LoadAllMngUnit()))
            {
                this.ManagementUnitCollection = _mngUnitRepository.GetMngUnitCollection();
            }
        }

        #endregion

        #region Value Property

        private RegisterPrinting _registerPrinting;

        bool CanNext
        {
            get { return _registerPrinting.IsValid; }
        }

        #endregion

        #region Presentation Property

        public string InvoiceUNK
        {
            get
            {
                return _registerPrinting.InvoiceUNK;
            }
            set
            {
                if (value != _registerPrinting.InvoiceUNK)
                {
                    _registerPrinting.InvoiceUNK = value;
                    base.OnPropertyChanged("InvoiceUNK");
                }
            }
        }

        public string InvoiceName
        {
            get
            {
                return _registerPrinting.InvoiceName;
            }
            set
            {
                if (value != _registerPrinting.InvoiceName)
                {
                    _registerPrinting.InvoiceName = value;
                    base.OnPropertyChanged("InvoiceName");
                }
            }
        }

        public int Number
        {
            get
            {
                return _registerPrinting.Number;
            }
            set
            {
                if (value != _registerPrinting.Number)
                {
                    _registerPrinting.Number = value;
                    base.OnPropertyChanged("Number");
                }
            }
        }
        public DateTime StartDate
        {
            get
            {
                return _registerPrinting.StartDate;
            }
            set
            {
                if (value != _registerPrinting.StartDate)
                {
                    _registerPrinting.StartDate = value;
                    base.OnPropertyChanged("StartDate");
                    base.OnPropertyChanged("ExpireDate");
                }
            }
        }
        public DateTime ExpireDate
        {
            get
            {
                return _registerPrinting.ExpireDate;
            }
            set
            {
                if (value == _registerPrinting.ExpireDate)
                    return;

                _registerPrinting.ExpireDate = value;
                base.OnPropertyChanged("StartDate");
                base.OnPropertyChanged("ExpireDate");
            }
        }
        public string ReceiverUNK
        {
            get
            {
                return _registerPrinting.ReceiverUNK;
            }
            set
            {
                if (value == _registerPrinting.ReceiverUNK)
                    return;

                _registerPrinting.ReceiverUNK = value;

                base.OnPropertyChanged("ReceiverUNK");
            }
        }
        public List<ManagementUnit> ManagementUnitCollection
        {
            get;
            set;
        }
        public int MngUnitIndex { get; set; }
        public FixedDocumentSequence MyDocument { get; set; }
        public bool PreviewSelected { get; set; }
        #endregion

        #region IDataErrorInfo Members

        string IDataErrorInfo.Error
        {
            get { return (_registerPrinting as IDataErrorInfo).Error; }
        }

        string IDataErrorInfo.this[string propertyName]
        {
            get
            {
                string error = null;
                error = (_registerPrinting as IDataErrorInfo)[propertyName];
                // Dirty the commands registered with CommandManager,
                // such as our Save command, so that they are queried
                // to see if they can execute now.
                CommandManager.InvalidateRequerySuggested();
                return error;
            }
        }

        #endregion // IDataErrorInfo Members

        #region Command
        private RelayCommand _next;
        public ICommand NextCommand
        {
            get
            {
                if (_next == null)
                {
                    _next = new RelayCommand(
                        (param) => this.Next(), param => this.CanNext);
                }
                return _next;
            }
        }

        private RelayCommand _close;
        public ICommand CloseCommand
        {
            get
            {
                if (_close == null)
                {
                    _close = new RelayCommand(
                        (param) => this.Cancel());
                }
                return _close;
            }
        }

        #endregion

        #region Command Methods

        void Cancel()
        {
            commandExcuted = "Cancel";
            OnRequestClose();
        }

        void Next()
        {
            ViewThongbaoPhathanhHD();
            ViewQDTuInHD();

            if (RegisterPrintingRepository.AddNewRegister(_registerPrinting))
            {
                RegResult = "Register Successfully!!!";
            }
            else
            {
                RegResult = "Register Failed!!!";
            }

            commandExcuted = "Next";
            OnRequestClose();
        }

        byte[] LoadFileContent(string filePath)
        {
            byte[] fileContent = null;
            try
            {
                FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(fileStream);
                long _TotalBytes = new System.IO.FileInfo(filePath).Length;
                fileContent = _BinaryReader.ReadBytes((Int32)_TotalBytes);
                return fileContent;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        void ViewThongbaoPhathanhHD()
        {
            
            string currentWorkingFolder = Directory.GetCurrentDirectory();
            string filePath = currentWorkingFolder + "\\" + "ThongbaoPhathanhHD.xaml";
            InvoicePrinter invoicePrinter = new InvoicePrinter(LoadFileContent(filePath)); ////hardcode template id
            invoicePrinter.PutSpan("spanCompanyName", _companyInfo.Name);
            invoicePrinter.PutSpan("spanTaxCode", _companyInfo.Taxcode);
            invoicePrinter.PutSpan("spanAddress", _companyInfo.Address);
            invoicePrinter.PutSpan("spanPhoneNumber", _companyInfo.Phone);
            invoicePrinter.PutSpan("spanDate", DateTime.Now.DayOfWeek.ToString());
            invoicePrinter.PutSpan("spanDay", DateTime.Now.Day.ToString());
            invoicePrinter.PutSpan("spanMonth", DateTime.Now.Month.ToString());
            invoicePrinter.PutSpan("spanYear", DateTime.Now.Year.ToString());
            invoicePrinter.PutSpan("spanReceiver", ManagementUnitCollection[MngUnitIndex].MngUnitName);
            string tableName = "tableContent";
            DataTable dataTable = new DataTable();
            for (int i = 0; i < 12; i++)
            {
                dataTable.Columns.Add(i.ToString());
            }
            DataRow row = dataTable.NewRow();
            row[0] = 1;
            row[1] = _invoiceTemplateCollection[TemplateRowIndex].Name;
            row[3] = _invoiceTemplateCollection[TemplateRowIndex].Code;
            row[4] = Number;
            row[7] = this.StartDate.ToShortDateString();
            dataTable.Rows.Add(row);
            invoicePrinter.PutDataTable(tableName, dataTable);

            if (PreviewSelected)
                invoicePrinter.ShowPrintPreview();
            invoicePrinter.Print(false);
        }

        void ViewQDTuInHD()
        {
            string currentWorkingFolder = Directory.GetCurrentDirectory();
            string filePath = currentWorkingFolder + "\\" + "QuyetdinhTuinHD.xaml";
            InvoicePrinter invoicePrinter = new InvoicePrinter(LoadFileContent(filePath)); ////hardcode template id
            //InvoicePrinter invoicePrinter = new InvoicePrinter("inv1f37dbfb-eaa2-4ad6-9cdc-ee061cd0b"); ////hardcode template id
            invoicePrinter.PutSpan("spanCompany", _companyInfo.Name);
            invoicePrinter.PutSpan("spanCompanyName1", _companyInfo.Name);
            invoicePrinter.PutSpan("spanCompanyName2", _companyInfo.Name);
            invoicePrinter.PutSpan("spanDate", DateTime.Now.DayOfWeek.ToString());
            invoicePrinter.PutSpan("spanDay", DateTime.Now.Day.ToString());
            invoicePrinter.PutSpan("spanMonth", DateTime.Now.Month.ToString());
            invoicePrinter.PutSpan("spanYear", DateTime.Now.Year.ToString());
            invoicePrinter.PutSpan("spanNow", DateTime.Now.ToShortDateString());
            invoicePrinter.PutSpan("spanStartDate", StartDate.ToShortDateString());
            invoicePrinter.PutSpan("spanGD", _companyInfo.Director);
            invoicePrinter.PutSpan("spanReceiver", ManagementUnitCollection[MngUnitIndex].MngUnitName);
            StringBuilder strHTTB = new StringBuilder();
            strHTTB.AppendFormat("+ Tên máy tính: {0}                                        ", _regInfo.ComputerName + System.Environment.NewLine);
            strHTTB.AppendFormat("+ Mã hiệu: {0}                                        ", _regInfo.ComputerCode + System.Environment.NewLine);
            strHTTB.AppendFormat("+ Hệ điều hành: {0}                                        ", _regInfo.OperatingName + System.Environment.NewLine);
            strHTTB.AppendFormat("+ Vi xử lý: {0}                                        ", _regInfo.CPUName + System.Environment.NewLine);
            strHTTB.AppendFormat("+ RAM: {0}                                        ", _regInfo.RamInfo + System.Environment.NewLine);
            strHTTB.AppendFormat("+ Yêu cầu: {0}                                        ", _regInfo.RequireInfo + System.Environment.NewLine);
            strHTTB.AppendFormat("+ Tên máy in: {0}                                        ", _regInfo.PrinterInfo + System.Environment.NewLine);
            strHTTB.AppendFormat("+ Nhà sản xuất: {0}                                        ", _regInfo.PrinterProducer + System.Environment.NewLine);
            strHTTB.AppendFormat("+ Yêu cầu: {0}", _regInfo.PrinterRequireInfo);
            invoicePrinter.PutSpan("spanHTTB", strHTTB.ToString());
            invoicePrinter.PutSpan("spanHD", "Tên hóa đơn: "+_invoiceTemplateCollection[TemplateRowIndex].Name);
            if (PreviewSelected)
                invoicePrinter.ShowPrintPreview();
            invoicePrinter.Print(false);
        }

        #endregion

        #region Display Invoice Template View

        /// <summary>
        /// Represent ItemSource for select property selected in search dialog
        /// </summary>
        public Dictionary<string, string> InvoiceTemplateField { get; set; }

        /// <summary>
        /// Represent Property for search selected in search dialog
        /// </summary>
        public string SelectTemplateProperty { get; set; }

        /// <summary>
        /// Represent Search Criteria typed in search dialog
        /// </summary>
        public string SearchTemplateCriteria { get; set; }

        /// <summary>
        /// Represent Index of row in listview selected in search dialog
        /// </summary>
        public int TemplateRowIndex { get; set; }

        /// <summary>
        /// Represent DataSource of listview for selecting product in search dialog
        /// </summary>
        public List<InvoiceTemplate> InvoiceTemplateCollection
        {
            get { return this._invoiceTemplateCollection; }
            set { this._invoiceTemplateCollection = value; base.OnPropertyChanged("InvoiceTemplateCollection"); }
        }

        private RelayCommand _displayTemplateCommand;
        private RelayCommand _selectTemplateCommand;
        private RelayCommand _closeTemplateCommand;
        private RelayCommand _searchTemplateCommand;
        views.windows.AllInvoiceTemplate supdlg = null;

        public ICommand DisplayTemplateViewCommand
        {
            get
            {
                if (_displayTemplateCommand == null)
                {
                    _displayTemplateCommand = new RelayCommand(
                        (param) => this.DisplayTemplateView()
                        );
                }
                return _displayTemplateCommand;
            }
        }

        public ICommand SelectTemplateCommand
        {
            get
            {
                if (_selectTemplateCommand == null)
                {
                    _selectTemplateCommand = new RelayCommand(
                        (param) => this.SelectTemplate()
                        );
                }
                return _selectTemplateCommand;
            }
        }

        public ICommand CloseTemplateCommand
        {
            get
            {
                if (_closeTemplateCommand == null)
                {
                    _closeTemplateCommand = new RelayCommand(
                        (param) => this.CloseTemplate()
                        );
                }
                return _closeTemplateCommand;
            }
        }

        public ICommand SearchTemplateCommand
        {
            get
            {
                if (_searchTemplateCommand == null)
                {
                    _searchTemplateCommand = new RelayCommand(
                        (param) => this.SearchTemplate()
                        );
                }
                return _searchTemplateCommand;
            }
        }

        /// <summary>
        /// Execute search button (on search dialog)
        /// </summary>
        private void SearchTemplate()
        {
            if (string.IsNullOrEmpty(this.SelectTemplateProperty))
            {
                this._invoiceTemplateRepository.LoadAllUnRegInvoiceTemplate();
                this.InvoiceTemplateCollection = this._invoiceTemplateRepository.GetInvoiceTemplate();
            }
            else
            {
               
            }
        }

        /// <summary>
        /// Execute select product function (on search dialog)
        /// </summary>
        private void SelectTemplate()
        {
            this.supdlg.DialogResult = true;
            this.supdlg.Close();
        }

        /// <summary>
        /// Execute close/cancel function (on search dialog)
        /// </summary>
        private void CloseTemplate()
        {
            this.supdlg.DialogResult = false;
            this.supdlg.Close();
        }

        private void DisplayTemplateView()
        {
            supdlg = new views.windows.AllInvoiceTemplate();
            supdlg.DataContext = this;
            if (supdlg.ShowDialog() == true)
            {
                this.InvoiceUNK = this._invoiceTemplateCollection[TemplateRowIndex].InvoiceUNK;
                this.InvoiceName = this._invoiceTemplateCollection[TemplateRowIndex].Name;
            }
        }
        #endregion
    }
}
